// SlagCar/DriverTransit/DriverTransit.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeKey: 0,   // 侧边导航
    activeName: '', // 折叠面板

    areaList: [], // 区域
    orderList: [],  // 订单
  },
  // 区域 侧边导航变化
  onSidebarChange(event) {
    let index = event.detail,
      {areaList} = this.data;
    if (!areaList[index]) {
      this.getAreaOrder();
      return
    }
    let {quyu_id} = areaList[index];
    this.getAreaOrder(quyu_id);
    this.setData({activeName: ''})
  },
  // 订单 折叠面板变化
  onCollapseChange(event) {
    let index = event.detail;
    if (index === '') {
      this.setData({activeName: event.detail,});
      return
    }
    let {orderList} = this.data,
      {order_id,children} = orderList[index];
    if (!children){
      this.getDestination(order_id).then(data =>{
        orderList[index].children = data;

        this.setData({
          activeName: event.detail,
          orderList
        });
      });
    }else {
      this.setData({
        activeName: event.detail,
      });

    }

  },

  // 消纳场 点击领取
  bindReceive(e){
    wx.showModal({
      title: '领取任务',
        content: '确定领取该任务？',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm){
          let {oid,did} = e.currentTarget.dataset;
          this.bindSubmit(oid,did)
        }

      },

    })
  },

  // 获取区域
  getArea(){
    wx.showLoading({mask: true});
    let url = 'ZTAuth/MuckOrderQuyu',
      param = {'page.no': 1,'page.size': 0}
    wx.$get(5,url,param).then(res =>{
      if (res.errcode != 0) return;
      let data = res.data.row || [];
      data = data.filter(item => item.quyu_id)
      data.push({quyu_id: null,quyu_name: '其他'});
      let obj = {areaList: data}
      if (data[0]){
        this.getAreaOrder(data[0].quyu_id)
      } else {
        wx.hideLoading();
      }
      this.setData(obj);
    })

  },
  // 获取区域订单
  getAreaOrder(id){
    wx.showLoading({mask: true});
    let url = 'ZTAuth/MuckOrdersByQuyu',
      param = {'page.no': 1,'page.size': 0};
    if (!id) param.is_empty_quyu = true
    else param.quyu_id = id;

    wx.$get(5,url,param).then(res =>{
      if (res.errcode != 0) return;
      let data = res.data.row || [],
        data0 = data[0],
        obj = {orderList: data};
      wx.hideLoading();
      this.setData(obj);
    })

  },
  //获取任务
  getDestination(id){
    return new Promise(resolve => {
      wx.showLoading({mask: true});
      let url = 'DynamicQuery/query_dynamic_v3',
        post = {
          "oby":"muck_order_assign_destination.row_id",
          "table_id":"muck_order_assign_destination",
          "page":1,"limit":0,
          "SearchWhere":{
            "filters": [
              {"CompareWith":"muck_order_assign_destination.parent_row_id","Operator":"=","CompareValue": id,"or":0},
              {"CompareWith":"muck_order_assign_destination.is_used","Operator":"=","CompareValue": true,"or":0},
            ],
            type: 'and'
          }
        };
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        wx.hideLoading();
        let data = res.data.row || [];
        resolve(data);
        // this.setData({destinationList: data})
      })
    })
  },

  //提交运输任务
  bindSubmit(oid,did){
    let post = {
        "order_row_id": oid,
        "order_assign_destination_row_id": did
      },
      url = 'ZTAuth/make_driver_waybill';
    wx.showLoading({mask: true});
    wx.$post(5,url,post,).then(res => {
      if (res.errcode != 0) {
        if (res.errmsg === '有未完成的运单不可再接新单') {
          this.getIncompleteOrder().then(res => {
            if (res){
              setTimeout(() =>{
                wx.navigateTo({
                  url: '../WaybillDetail/WaybillDetail?row_id=' + res.row_id
                })
              },1000)
            }
          });
        }
        return;
      }
      wx.$toast('提交成功');
      this.getIncompleteOrder().then(res => {
        if (res){
          setTimeout(() =>{
            wx.navigateTo({
              url: '../WaybillDetail/WaybillDetail?row_id=' + res.row_id
            })
          },1000)
        }
      });
    })

  },

  // 获取司机未完成订单
  getIncompleteOrder(){
    return new Promise(resolve => {
      let url = 'ZTAuth/driver_waybill_incomplete';
      wx.$get(5,url).then(res => {
        if (res.errcode != 0) return;
        let data = res.data.row && res.data.row[0];
        resolve(data)
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getIncompleteOrder().then(data => {
      if (data){
        wx.showModal({
          title: '运单进行中',
          content: '当前有运单进行中，跳转到运单详情',
          confirmText: '跳转',
          success: (res) => {
            if(res.confirm) {
              wx.navigateTo({
                url: '../WaybillDetail/WaybillDetail?row_id=' + data.row_id
              })
            }
          },
        })
      }
    })
    this.getArea();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
